import path = require('path')
import { FileUtil } from 'tools-mock'

const iconUrl = path.join(__dirname, '../../public/vicon')
const iconOutUrl = path.join(__dirname, '../../public/viconUniapp')

const tsTemp = (name: string, value: any) => {
    return `
export const ${name}Json = ${value}

export const ${name}Name = '${name}'

export type ${name} = keyof typeof ${name}Json`
}

/**
 * 对所有图标库的json转为ts文件并生成uniapp的index组件
 */
const init = async () => {
    const iconMap = {} as any

    await FileUtil.readDirectory(iconUrl, async (filename) => {
        if (filename.endsWith('_all.json')) {
            const name = filename.split(iconUrl)[1].substring(1).split('/')[0]
            const val = await FileUtil.readFile(filename)
            iconMap[name] = val
        }
    })

    const keys = Object.keys(iconMap)
    let v1 = ''
    let v2 = ''
    let v3 = ''

    let indexStr: string = await FileUtil.readFile(path.resolve('./src/getAllCom.vue'))
    for (let i = 0; i < keys.length; i++) {
        const key = keys[i]
        v1 += `import { ${key}Json, ${key}Name, type ${key} } from './${key}'
`
        v2 += `    [${key}Name]: ${key}Json,
`
        v3 += `| ${key} `
        await FileUtil.writeFile(path.join(iconOutUrl, key + '.ts'), tsTemp(key, iconMap[key]))
    }
    indexStr = indexStr.replace('__v1', v1)
    indexStr = indexStr.replace('__v2', v2)
    indexStr = indexStr.replace('__v3', v3.substring(1))
    await FileUtil.writeFile(path.join(iconOutUrl, 'index.vue'), indexStr)
}

init()
